package arrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 合并区间
 */
public class Merge {
    public static void main(String[] args) {
        int[][] intervals = {{1, 4}, {0, 4}};

        if (intervals.length == 0) {
//            return new int[0][2];
        }
        int[][] temp = new int[intervals.length][2];
        intervals = Arrays.stream(intervals).sorted((a, b) -> a[0] - b[0]).toArray(int[][]::new);
        int[] arr = new int[2];
        //TODO当确定数组结果的长度小于等于数组长度的时候可以用list
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            arr = intervals[i];
            while (i < intervals.length - 1 && (arr[1] >= intervals[i + 1][0])) {//1.当不满足前一个的右断点大于后一个的左断点的时候直接跳过
                arr[1] = Math.max(arr[1], intervals[i + 1][1]);
                i++;
            }
            list.add(arr);
        }
        temp= list.toArray(int[][]::new);
        System.out.print("[");
        for (int i = 0; i < list.size(); i++) {
            System.out.print("[" + temp[i][0] + "," + temp[i][1] + "]");
            if (i < list.size() - 1) {
                System.out.print(",");
            }
        }
        System.out.print("]");
    }
}
